package com.example.springfortestspace.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.springfortestspace.LogUtil;
import com.example.springfortestspace.dao.TestSpaceDao;
import com.example.springfortestspace.entity.Customer;
import com.google.gson.Gson;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @Auther：FKM
 * @Date：2024/5/1011:16
 */
@Service
public class DoForJarService {


    @Autowired
    private TestSpaceDao testSpaceDao;


    @Autowired
    private  SchedulTaskService schedulTaskService;
    /**
     *给前端调用的统一进入接口
     */
    @Transactional(rollbackFor = Exception.class,readOnly = false)
    public Customer doForproject(String data){
        Customer  cus =  new Customer();
        Gson gson = new Gson();
        String jar[] = new String[4];
        Map<String,String> map = gson.fromJson(data, HashMap.class);
        Map<String, String> finalMap = map;
        map.keySet().forEach(p ->{
             if(p.contains(".jar")){
                 jar[0] = finalMap.get(p);//jar包地址
             }else if(p.contains("ilc-wms-web.zip")){
                 jar[1] = finalMap.get(p);//前端包地址（zip格式）
             }else if(p.contains("ilc-supplier-web.zip")){
                 jar[2] = finalMap.get(p);//前端包地址（zip格式）
             }else{
                 jar[3] = finalMap.get(p);
             }
         });

        String jarpath = jar[0];
        String webpath = jar[1];
        String webSuppath = jar[2];
        String cusData = jar[3];
        System.out.println("jarpath ===" + jar[0]+"webpath ===="+jar[1]+"webSuppath ===="+jar[2]+"cusData ===="+jar[3]);
        LogUtil.WriteToLogFile("jarpath ===" + jar[0]+"webpath ===="+jar[1]+"webSuppath ===="+jar[2]+"cusData ===="+jar[3]);
        String[] split = cusData.split("-");
        String customName = "";
        String version = "";
        List<String> list = Arrays.asList(split);
        boolean otFlag = false;
        if(list.contains("ot")){
            otFlag = true;
        }
        for (int i = 0; i < split.length; i++) {
            if(otFlag){
                if(split[i].equals("ot")){
                    version = "ot";
                    if((split[i+1].startsWith("v") || split[i+1].startsWith("V") )  && split.length > 2){
                        customName = split[i+2];
                    }else {
                        customName = split[i+1];
                    }
                }
            }else{
                if(split[i].startsWith("v") || split[i].startsWith("V")){
                    version = split[i].replace(".","").replace("v","").replace("V","");
                    customName = split[i + 1];
                }
            }
        }
//        customName = split[1];
//        version = split[0].replace(".","").replace("v","").replace("V","");
        System.out.println("customName ===" + customName+"version ===="+version);
        LogUtil.WriteToLogFile("customName ===" + customName+"version ===="+version);
        try{
            initFilePath(customName,version);//初始化项目路径，也就是预先将相关数据整备到壳中。
            System.out.println("初始化结束");
            moveFile(customName,version,jarpath);//"复制Jar包以及两个压缩包"
            String webTargetFilepath  = "/data/custom/"+version+"/"+customName+"/ilc-wms-test/ilc-wms-web";
            String webSupTargetFilepath  = "/data/custom/"+version+"/"+customName+"/ilc-wms-test/ilc-supplier-web";
            zipLoad(webpath,webTargetFilepath,customName);
            zipLoad(webSuppath,webSupTargetFilepath,customName);
            modifyTextFile(customName,version,cus);//修改前端配置文件
            doForProperties(customName,version,cus);//修改peopertise
            cus.setId(IdUtil.simpleUUID());
            cus.setCustomName(customName);
            cus.setVersion(version);
            cus.setCreateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            cus.setUpdateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            runProject(cus);
        }catch (Exception e){
            e.printStackTrace();
            LogUtil.WriteToLogFile("客户"+customName+"出现错误 === " + e.getMessage()+" \n");
            return new Customer();
            //throw new Exception(e.getMessage());
        }

        return cus;
    }




    /**
     * jar包转移的方法
     */
    public void moveFile(String customName,String version,String sourcePath) throws IOException {
        String sourceFilePath = sourcePath;
        String targetFilePath = "/data/custom/"+version+"/"+customName+"/ilc-wms-test/app_backend/lib/";
        LogUtil.WriteToLogFile("客户"+customName+"sourceFilePath ==== " +sourceFilePath);
        LogUtil.WriteToLogFile("客户"+customName+"targetFilePath ==== " +targetFilePath);
        try {
            String commond = "cp "+sourceFilePath+" "+targetFilePath;
            LogUtil.WriteToLogFile("移动jar包的命令 === " + commond );
            Process process2 = Runtime.getRuntime().exec(commond);
            int i2 = process2.waitFor();
            LogUtil.WriteToLogFile("移动jar包结束 ===  "+ i2 );
            process2.destroy();

        }catch(IOException | InterruptedException e){
            e.printStackTrace();
            LogUtil.WriteToLogFile("移动jar包的出错 === " + e.getMessage() );
        }

    }

    /**
     * 解压压缩包
     */
        public void zipLoad(String webZipPath,String webTarget,String customName){
            String zipFilePath = webZipPath;
            String webTargetFilepath  = webTarget;
            File web = new File(webTargetFilepath);

            System.out.println("zipFilePath ===" + zipFilePath);
            System.out.println("webTarget ===" + webTarget);
            LogUtil.WriteToLogFile("客户"+customName+"zipFilePath ==== " +zipFilePath);
            LogUtil.WriteToLogFile("客户"+customName+"webTarget ==== " +webTarget);
            try {
                if(web.exists()){
                   // System.out.println("这里进入删除");
                    LogUtil.WriteToLogFile("这里进入删除");
                    Process process = Runtime.getRuntime().exec("rm -rf"+" " +webTarget);
                    int i = process.waitFor();
                    LogUtil.WriteToLogFile("删除完成,命令码" +i);
                    process.destroy();
                    Process process2 = Runtime.getRuntime().exec("mkdir"+" " +webTarget);
                    int mk = process2.waitFor();
                   // System.out.println();
                    LogUtil.WriteToLogFile("存在时创建完成,命令码" +mk);
                    process2.destroy();
                }else{
                    Process process2 = Runtime.getRuntime().exec("mkdir"+" " +webTarget);
                    int mk = process2.waitFor();
                    //System.out.println("创建完成,命令码" +mk);
                    LogUtil.WriteToLogFile("不存在时创建完成,命令码" +mk);
                    process2.destroy();
                }
                Process process = Runtime.getRuntime().exec("unzip"+" " +zipFilePath +" -d " + webTarget);
                int zi = process.waitFor();
                System.out.println("解压完成,命令码" +zi);
                System.out.println("解压完成！");
                LogUtil.WriteToLogFile("客户"+customName+"解压完成！");
                process.destroy();
            }catch (InterruptedException e){
                LogUtil.WriteToLogFile("zipLoad报错====="+e.getMessage());
            } catch (IOException e) {
                LogUtil.WriteToLogFile("zipLoad报错====="+e.getMessage());
                e.printStackTrace();
            }



        }


    /**
     * 修改peopertise文件的方法
     */
    public void doForProperties(String customName,String version, Customer cus){
        System.out.println("准备开始修改后端程序配置文件");
        LogUtil.WriteToLogFile("客户"+customName+"准备开始修改后端端程序配置文件 ");
        String propath = "/data/custom/"+version+"/"+customName+"/ilc-wms-test/app_backend/conf/application.properties";
        System.out.println("propath ====" + propath);
        String dblowCase= customName.toLowerCase();
        String dbName ="ilc_wms_" + dblowCase; //数据库名称规则，必须是下划线
        // #db
        cus.setDbName(dbName);
        // 要追加的键值对
        String[] keyValuePairs = {
                "dbUrl.database="+dbName,
                "serverPort="+cus.getServerPort(),
                "spring.redis.database="+cus.getRedisDBname(),
        };
        try {
            // 读取properties文件
            BufferedWriter writer = new BufferedWriter(new FileWriter(propath, true));
            for (String pair : keyValuePairs) {
                writer.write(pair);
                writer.newLine();
            }
            writer.close();
            System.out.println("修改完毕");
            LogUtil.WriteToLogFile("客户"+customName+"修改完毕 ");
        } catch (IOException e) {
            LogUtil.WriteToLogFile(e.getMessage());
            e.printStackTrace();
        }
    }

    //修改conf文件
    void modifyTextFile(String customer,String version,Customer cus){
        System.out.println("准备开始修改前端程序配置文件");
        LogUtil.WriteToLogFile("客户"+customer+"准备开始修改前端程序配置文件 ");
        StringBuilder conf = new StringBuilder();
        Customer byCustomNameAndVersion = testSpaceDao.findByCustomNameAndVersion(customer, version);
        if(byCustomNameAndVersion != null){ //如果原本启动过，就用原本的端口，不占用新端口
            System.out.println("当前数据启动的对应端口 ==== " + byCustomNameAndVersion.getServerPort());
            createConfForWeb(customer,version,conf,Integer.valueOf(byCustomNameAndVersion.getWmsFrontEndPort()),Integer.parseInt(byCustomNameAndVersion.getServerPort()));
            createConfForSupWeb(customer,version,conf,Integer.valueOf(byCustomNameAndVersion.getWmsFrontEndSupPort()),Integer.parseInt(byCustomNameAndVersion.getServerPort()));
            cus.setRedisDBname(byCustomNameAndVersion.getRedisDBname());
            cus.setServerPort(byCustomNameAndVersion.getServerPort());
            cus.setWmsFrontEndPort(byCustomNameAndVersion.getWmsFrontEndPort());
            cus.setWmsFrontEndSupPort(byCustomNameAndVersion.getWmsFrontEndSupPort());
            System.out.println("后端端口预计:" + cus.getServerPort() + "--前端WMS对应端口应该是 :" + cus.getWmsFrontEndPort()+"--前端供应商对应端口应该是："+cus.getWmsFrontEndSupPort());
            LogUtil.WriteToLogFile("后端端口预计:" + cus.getServerPort() + "--前端WMS对应端口应该是 :" + cus.getWmsFrontEndPort()+"--前端供应商对应端口应该是："+cus.getWmsFrontEndSupPort());
        }else{ //如果本身没有启动过，就获取当前表中最大端口号，向下流
            Customer maxProjectPror = testSpaceDao.findMaxProjectPror();
            Integer maxser = 0;
            Integer maxweb = 0;
            Integer maxwebSupplier = 0;
            Integer redisName = 1;
            if(null !=maxProjectPror ){
                maxser = Integer.parseInt(maxProjectPror.getMaxServer())+1;
                maxweb = Integer.parseInt(maxProjectPror.getMaxWebPort())+1;
                maxwebSupplier = Integer.parseInt(maxProjectPror.getMaxWebSupPort())+1;
                redisName = Integer.parseInt(maxProjectPror.getMaxRedis())+1;
                if(maxser == 8085){
                    maxser += 2;
                }else if(maxweb == 8180){
                    maxweb += 1;
                }else if (maxwebSupplier == 9190) {
                    maxweb += 1;
                }
            }else{
                maxser = 8001;
                maxweb = 8101;
                maxwebSupplier = 9101;
            }

            while(!checkPort(maxser)){
                maxser += 1;
            }
            while(!checkPort(maxweb)){
                maxweb += 1;
            }
            while(!checkPort(maxwebSupplier)){
                maxwebSupplier += 1;
            }
            createConfForWeb(customer,version,conf,maxweb,maxser); //wms 前端配置文件
            createConfForSupWeb(customer,version,conf,maxwebSupplier,maxser);//sup-wms 前端配置文件
            cus.setServerPort(maxser+"");
            cus.setWmsFrontEndPort(maxweb+"");
            cus.setWmsFrontEndSupPort(maxwebSupplier+"");
            cus.setRedisDBname(redisName+"");
            System.out.println("后端端口预计:" + maxser + "--前端WMS对应端口应该是 :" + maxweb+"--前端供应商对应端口应该是："+maxwebSupplier);
            LogUtil.WriteToLogFile("客户"+customer+"后端端口预计:" + maxser + "--前端WMS对应端口应该是 :" + maxweb+"--前端供应商对应端口应该是："+maxwebSupplier);
        }
        ///data/soft/1Panel/1panel/apps/openresty/openresty/conf/conf.d
        String filePath = "/data/soft/1Panel/1panel/apps/openresty/openresty/conf/conf.d/"+customer+".conf";
        try(FileWriter writer = new FileWriter(filePath)) {
            String s = conf.toString();
            writer.write(s);
        } catch (IOException e) {
            LogUtil.WriteToLogFile("客户"+customer+"修改前端配置文件报错"+e.getMessage());
            e.printStackTrace();
            return;
        }
    }

    /**
     *检查端口是不是被占用
     */
    boolean checkPort(int port){
        boolean flag = true;
        try{
            ServerSocket serverSocket = new ServerSocket(port);
            // 如果能够成功创建 ServerSocket 对象，则说明端口未被占用
            System.out.println("端口 " + port + " 未被占用");
            serverSocket.close();
        }catch (Exception e){
            flag = false;
        }
       return flag;
    }

    /**
     * 配置结束开始启动项目
     */
    public void runProject(Customer cus){
        //启动前先存一笔数据
        LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"进入启动方法");
        Customer byCustomNameAndVersion = testSpaceDao.findByCustomNameAndVersion(cus.getCustomName(), cus.getVersion());
        if(null == byCustomNameAndVersion){
            cus.setStatus("1"); //运行中
            testSpaceDao.insertIntoTable(cus);
        }else{
            cus.setStatus("1");//运行中
            cus.setUpdateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            testSpaceDao.updateIntoTableStatus(cus);
            cus.setId(byCustomNameAndVersion.getId());
        }
        //判断是否启动：


        //启动后端
        String scriptPath = "/data/custom/"+cus.getVersion()+"/"+cus.getCustomName()+"/ilc-wms-test/app_backend/platform/bin/run.sh";
        try{
            File pidFile = new File("/data/custom/"+cus.getVersion()+"/"+cus.getCustomName()+"/ilc-wms-test/app_backend/DWApiGatewayApplication.pid");
            if(pidFile.exists()){ //不存在就代表没有启动过，那就直接启动，存在就代表已经启动了，要先停止再启动。
                String stoptPath = "/data/custom/"+cus.getVersion()+"/"+cus.getCustomName()+"/ilc-wms-test/app_backend/platform/bin/stop.sh";
                Process processStop = Runtime.getRuntime().exec(stoptPath);
                int stop = processStop.waitFor();
                if(stop == 0){
                    LogUtil.WriteToLogFile("项目已经停止");
                }
                processStop.destroy();
            }
            LogUtil.WriteToLogFile("启动项目路径 ====" +scriptPath);
            System.out.println("启动项目路径 ====" +scriptPath);
            Process processRun = Runtime.getRuntime().exec(scriptPath);
            int runi = processRun.waitFor();
            processRun.destroy();
           // Process start = jarProcess.start();
            if (runi == 0) {
                System.out.println("jar运行成功!");
                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"jar运行成功 ");
            } else {
                System.out.println("jar运行失败！");
                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"jar运行失败 ");
            }
            //启动前端
            Process process2 = Runtime.getRuntime().exec("docker exec cb6e0336567c nginx -s reload");
            // 等待命令执行完成
            int exitCode = process2.waitFor();
            process2.destroy();
            if (exitCode == 0) {
                System.out.println("Nginx 配置文件已重新加载");
                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"Nginx 配置文件已重新加载 ");
            } else {
                System.out.println("无法重新加载 Nginx 配置文件");
                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"无法重新加载 Nginx 配置文件 ");
            }
            Thread.sleep(15000);
            //判断服务是否启动
            String urlString = "http://172.16.70.83:"+cus.getWmsFrontEndPort()+"/dapilc/restful/service/ilcwmsplus/IZlLanguageService/getAllZlLanguage"; // 要检查的URL
            HttpRequest requestForWms =  HttpRequest.post(urlString);
            HttpResponse executeWms = requestForWms.execute();
            int statusCode = executeWms.getStatus();
            System.out.println("statusCode ==== " + statusCode);
            if(statusCode == HttpURLConnection.HTTP_OK){
                cus.setStatus("0");//启动成功
                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"启动成功");
                cus.setUpdateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                testSpaceDao.updateIntoTableStatus(cus);
            }else{
                LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"启动失败");
                cus.setStatus("3");//启动失败
                cus.setUpdateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
                testSpaceDao.updateIntoTableStatus(cus);
            }

            //发请求启动socket
            System.out.println("===这里尝试发送请求给socket==id==" + cus.getId());
            LogUtil.WriteToLogFile("===这里尝试发送请求给socket==id==" + cus.getId());
            HttpRequest requestSockEt = HttpRequest.post("http://172.16.70.83:3030/api")
                    .form("id",cus.getId())
                    .form("filePath","/data/custom/"+cus.getVersion()+"/"+cus.getCustomName()+"/ilc-wms-test/app_backend/platform/log/Digiwin.log");
            HttpResponse socketRespons = requestSockEt.execute();
            int status = socketRespons.getStatus();
            if(status == HttpURLConnection.HTTP_OK){
                LogUtil.WriteToLogFile("连接socket成功");
            }else{
                LogUtil.WriteToLogFile("连接socket失败");
            }
            LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"socket请求发送完毕 ，报文====" + JSONUtil.toJsonStr(requestSockEt));
        }catch (MalformedURLException e){
            System.out.println("出现URL错误");
            LogUtil.WriteToLogFile("出现URL错误" + e.getMessage());
            e.printStackTrace();
        }catch (IOException e){
            System.out.println("连接超时或 Connection refused"+ e.getMessage());
            LogUtil.WriteToLogFile("连接超时或 Connection refused"+ e.getMessage());
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
            cus.setStatus("3");//启动失败
            cus.setUpdateDate(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            testSpaceDao.updateIntoTableStatus(cus);
            System.out.println(e.getMessage());
            LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"启动错误"+e.getMessage());
        }

    }



    StringBuilder createConfForWeb(String custom,String version,StringBuilder configuration,int webPort,int serverPort){//写入conf文件的模板
        configuration.append("server {\n");
        configuration.append("    listen              "+webPort+";\n");
        configuration.append("    server_name         localhost;\n");
        configuration.append("    #absolute_redirect   off;\n");
        configuration.append("\n");
        configuration.append("    access_log          /data/custom/"+version+"/"+custom+"/ilc-wms-test/ilc-wms-test.access.log    main;\n");
        configuration.append("    error_log          /data/custom/"+version+"/"+custom+"/ilc-wms-test/ilc-wms-test.error.log;\n");
        configuration.append("\n");
        configuration.append("    location / {\n");
        configuration.append("        root            /data/custom/"+version+"/"+custom+"/ilc-wms-test/ilc-wms-web;\n");
        configuration.append("        try_files       $uri    $uri/   /index.html;\n");
        configuration.append("    }\n");
        configuration.append("\n");
        configuration.append("    location /dapilc/ {\n");
        configuration.append("        proxy_set_header Host $host:$server_port;\n");
        configuration.append("        proxy_http_version 1.1;\n");
        configuration.append("        proxy_set_header Upgrade $http_upgrade;\n");
        configuration.append("        proxy_set_header Connection \"upgrade\";\n");
        configuration.append("        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n");
        configuration.append("\n");
        configuration.append("        proxy_pass  http://127.0.0.1:"+serverPort+"/;\n");
        configuration.append("    }\n");
        configuration.append("}\n\n");
        return configuration;
    }


    StringBuilder createConfForSupWeb(String custom,String version,StringBuilder configuration,int webPort,int serverPort){//写入conf文件的模板
        configuration.append("server {\n");
        configuration.append("    listen              "+webPort+";\n");
        configuration.append("    server_name         localhost;\n");
        configuration.append("    #absolute_redirect   off;\n");
        configuration.append("\n");
        configuration.append("    access_log          /data/custom/"+version+"/"+custom+"/ilc-wms-test/supplier.access.log    main;\n");
        configuration.append("    error_log           /data/custom/"+version+"/"+custom+"/ilc-wms-test/supplier.error.log;\n");
        configuration.append("\n");
        configuration.append("    location / {\n");
        configuration.append("        root            /data/custom/"+version+"/"+custom+"/ilc-wms-test/ilc-supplier-web;\n");
        configuration.append("        try_files       $uri    $uri/   /index.html;\n");
        configuration.append("    }\n");
        configuration.append("\n");
        configuration.append("    location /dapilc/ {\n");
        configuration.append("        proxy_set_header Host $host:$server_port;\n");
        configuration.append("        proxy_http_version 1.1;\n");
        configuration.append("        proxy_set_header Upgrade $http_upgrade;\n");
        configuration.append("        proxy_set_header Connection \"upgrade\";\n");
        configuration.append("        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n");
        configuration.append("\n");
        configuration.append("        proxy_pass  http://127.0.0.1:"+serverPort+"/;\n");
        configuration.append("    }\n");
        configuration.append("}\n\n");
        return configuration;
    }



    /**
     *给前端调用的统一进入接口
     */
    public Customer doForprojectTest(String data){
        Customer  cus =  new Customer();
        try {
            //关闭对应的项目环境
            String port = "8989";
            ProcessBuilder processBuilder = new ProcessBuilder();
            Process process = Runtime.getRuntime().exec("lsof -t -i :" + port);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("PID of process using port " + port + ": " + line);
            }
            process.waitFor();


        }catch(Exception e){
            e.printStackTrace();
        }


        return cus;
    }


    public Customer  doForprojectTestZip(String data){
        Customer  cus =  new Customer();
        Gson gson = new Gson();
        String jar[] = new String[4];
        Map<String,String> map = gson.fromJson(data, HashMap.class);
        Map<String, String> finalMap = map;
        map.keySet().forEach(p ->{
            if(p.contains(".jar")){
                jar[0] = finalMap.get(p);//jar包地址
            }else if(p.contains("frontend.zip")){
                jar[1] = finalMap.get(p);//前端包地址（zip格式）
            }else if(p.contains("supplier.zip")){
                jar[2] = finalMap.get(p);//前端包地址（zip格式）
            }else{
                jar[3] = finalMap.get(p);
            }
        });

        String jarpath = jar[0];
        String webpath = jar[1];
        String webSuppath = jar[2];
        String cusData = jar[3];
        System.out.println("jarpath ===" + jar[0]+"webpath ===="+jar[1]+"webSuppath ===="+jar[2]+"cusData ===="+jar[3]);
        String[] split = cusData.split("-");
        String customName = split[1];
        String version = split[0].replace(".","").replace("v","").replace("V","");
        System.out.println("customName ===" + customName+"version ===="+version);
        String sourceFilePath = jar[0];
        String targetFilePath = "/data/custom/222/"+customName+"/ilc-wms-test/app_backend/lib";
        // String webTargetFilepath  = "/data/custom/223/"+customName+"/ilc-wms-test";

        System.out.println("sourceFilePath =====" + sourceFilePath);
        System.out.println("targetFilePath =====" + targetFilePath);

        Path targetFile = Paths.get(targetFilePath);

        Path sourceFile = Paths.get(sourceFilePath);
        try {
      //  String webTargetFilepath  = "/data/custom/"+version+"/"+customName+"/ilc-wms-test/ilc-wms-web";
       // String webSupTargetFilepath  = "/data/custom/"+version+"/"+customName+"/ilc-wms-test/ilc-supplier-web";
      //  modifyTextFile(customName,version,cus);//修改前端配置文件
        doForProperties(customName,version,cus);//修改peopertise


//            if(Files.exists(targetFile)){
//                Files.createDirectories(targetFile);
//            }


        }catch(Exception e){
            e.printStackTrace();
        }


        return cus;
    }

    public String getAll(String data){
        List<Customer> customerList = new ArrayList<>();
        Gson gson = new Gson();
        Customer customer;
        customer = gson.fromJson(data, Customer.class);
        customerList = testSpaceDao.findAll(customer);
        String s = JSONUtil.toJsonStr(customerList);
        checkProjectStatus(customerList);
        System.out.println("查询到的数据 ==== " +s);
        LogUtil.WriteToLogFile("查询到的数据 ==== " +s);
        return s;
    }


    public void initFilePath(String customer,String version){
        String path = "/data/custom/"+version+"/"+customer;
        File file = new File(path);
        LogUtil.WriteToLogFile("初始化path ===="+path );
        try{
            if(!file.exists()){
                LogUtil.WriteToLogFile("这个项目路径已经不存在需要重新建立" );
                Process process1 = Runtime.getRuntime().exec("mkdir "+path);
                int i1 = process1.waitFor();
                LogUtil.WriteToLogFile("创建文件夹 === " + i1 );
                process1.destroy();
                File file2 = new File(path+"/ilc-wms-test/");
                if(!file2.exists()){
                    Process process2 = Runtime.getRuntime().exec("mkdir /data/custom/"+version+"/"+customer+"/ilc-wms-test" );
                    int i2 = process2.waitFor();
                    LogUtil.WriteToLogFile("不存在时==创建i2== "+ i2 );
                    process2.destroy();
                    LogUtil.WriteToLogFile("不存在时准备解压==path== "+ path );
                    if("ot".equals(version)){ //ot版本使用另一套壳来作为启动模板
                        String commond = "cp -r /data/custom/test/ot/ilc-wms-test/ /data/custom/"+version+"/"+customer+"/";
                        LogUtil.WriteToLogFile("ot执行复制的方法 ====" + commond);
                        Process process4 = Runtime.getRuntime().exec(commond);
                        int i4 = process4.waitFor();
                        process4.destroy();
                        LogUtil.WriteToLogFile("不存在时ot复制==i4== "+ i4 );
                    }else{//非ot版本使用一般版本
                        String commond = "cp -r /data/custom/test/ilc-wms-test/ /data/custom/"+version+"/"+customer+"/";
                        LogUtil.WriteToLogFile("非ot版本执行复制的方法 ====" + commond);
                        Process process4 = Runtime.getRuntime().exec(commond );
                        int i4 = process4.waitFor();
                        process4.destroy();
                        LogUtil.WriteToLogFile("不存在时非ot复制==i4== "+ i4 );
                    }
                }
            }else if(file.exists()){
                LogUtil.WriteToLogFile("这个项目路径已经存在不需要重新建立" );
                //新查询对应端口，看看服务是否在运行，，如果运行，则关闭进程。
                Customer byCustomNameAndVersion = testSpaceDao.findByCustomNameAndVersion(customer, version);
                List<Customer> cusList = new ArrayList<>();
                cusList.add(byCustomNameAndVersion);
                checkProjectStatus(cusList);
                Customer quaryAgine = testSpaceDao.findByCustomNameAndVersion(customer, version);
                String serverPort = quaryAgine.getServerPort();
                String status = quaryAgine.getStatus();
                if("0".equals(status)){
                    LogUtil.WriteToLogFile("这个项目是启动状态，要先关闭");
                    String runProcessPID = schedulTaskService.getRunProcessPID(serverPort);
                    if(!StringUtil.isNullOrEmpty(runProcessPID)){
                        Process killProcess = Runtime.getRuntime().exec("kill "+runProcessPID);
                        int i = killProcess.waitFor();
                        if(i == 0){
                            LogUtil.WriteToLogFile("客户"+customer+"服务关闭完成");
                            //关闭完成之后再删除，防止意外bug
                            Process process1 = Runtime.getRuntime().exec("rm -rf /data/custom/"+version+"/"+customer+"/*" );
                            int i1 = process1.waitFor();
                            process1.destroy();
                            System.out.println("i1先删除==== "+ i1);
                            LogUtil.WriteToLogFile("先删除，再复制");
                            File file2 = new File(path+"ilc-wms-test/");
                            Process process2 = Runtime.getRuntime().exec("mkdir /data/custom/"+version+"/"+customer+"/ilc-wms-test" );
                            int i2 = process2.waitFor();
                            LogUtil.WriteToLogFile("i2 == "+ i2 );
                            process2.destroy();
                            LogUtil.WriteToLogFile("存在时准备解压==path== "+ path );
                            if("ot".equals(version)){ //ot版本使用另一套壳来作为启动模板
                                String commond = "cp -r /data/custom/test/ot/ilc-wms-test/ /data/custom/"+version+"/"+customer+"/";
                                LogUtil.WriteToLogFile("ot执行复制的方法 ====" + commond);
                                Process process4 = Runtime.getRuntime().exec(commond);
                                    int i4x = process4.waitFor();
                                    process4.destroy();
                                    System.out.println("i4==== "+ i4x);
                             }else{//非ot版本使用一般版本
                                String commond = "cp -r /data/custom/test/ilc-wms-test/ /data/custom/"+version+"/"+customer+"/";
                                LogUtil.WriteToLogFile("非ot版本执行复制的方法 ====" + commond);
                                Process process4 = Runtime.getRuntime().exec(commond );
                                    int i4 = process4.waitFor();
                                    process4.destroy();
                                    System.out.println("i4==== "+ i4);
                             }

                        }else{
                            LogUtil.WriteToLogFile("客户"+customer+"服务关闭失败");
                        }
                    }
                }else{
                    LogUtil.WriteToLogFile("这个项目是关闭状态");
                    //关闭完成之后再删除，防止意外bug
                    Process process1 = Runtime.getRuntime().exec("rm -rf /data/custom/"+version+"/"+customer+"/*" );
                    int i1 = process1.waitFor();
                    LogUtil.WriteToLogFile("i1先删除完毕==== "+ i1);
                    process1.destroy();
                    LogUtil.WriteToLogFile("先删除，再复制");
                    Process process2 = Runtime.getRuntime().exec("mkdir /data/custom/"+version+"/"+customer+"/ilc-wms-test" );
                    int i2 = process2.waitFor();
                    LogUtil.WriteToLogFile("创建文件的i2 == "+ i2 );
                    process2.destroy();
                    LogUtil.WriteToLogFile("准备复制的==path== "+ path);
                    if("ot".equals(version)){ //ot版本使用另一套壳来作为启动模板
                        String commond = "cp -r /data/custom/test/ot/ilc-wms-test/ /data/custom/"+version+"/"+customer+"/";
                        LogUtil.WriteToLogFile("ot执行复制的方法 ====" + commond);
                        Process process4 = Runtime.getRuntime().exec(commond);
                        int i4x = process4.waitFor();
                        process4.destroy();
                        System.out.println("i4==== "+ i4x);
                    }else{//非ot版本使用一般版本
                        String commond = "cp -r /data/custom/test/ilc-wms-test/ /data/custom/"+version+"/"+customer+"/";
                        LogUtil.WriteToLogFile("非ot版本执行复制的方法 ====" + commond);
                        Process process4 = Runtime.getRuntime().exec(commond );
                        int i4 = process4.waitFor();
                        process4.destroy();
                        System.out.println("i4==== "+ i4);
                    }

                }
            }
        }catch (Exception e){
            System.out.println();
            e.printStackTrace();
        }
    }

    /**
     * 该方法预备给前端页面调用时，检查项目状态准确性
     */
    public void checkProjectStatus(List<Customer> list){
        for (Customer cus :
                list) {
            if ( ! ("标准222".equals(cus.getCustomName()) || "标准223".equals(cus.getCustomName()) )) { //不是222和223的默认状态是开启的不需要检查状态
                //判断服务是否启动
                try {
                    String urlString = "http://172.16.70.83:"+cus.getServerPort()+"/restful/service/ilcwmsplus/IZlLanguageService/getAllZlLanguage"; // 要检查的URL
                    HttpRequest requestForWms =  HttpRequest.post(urlString);
                    HttpResponse executeWms = requestForWms.execute();
                    int statusCode = executeWms.getStatus();
                    System.out.println("statusCode ==== " + statusCode);
                    LogUtil.WriteToLogFile("客户statusCode ===="+statusCode);
                    if(statusCode == HttpURLConnection.HTTP_OK){
                        cus.setStatus("0");//启动成功
                        LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"启动成功");

                        testSpaceDao.updateIntoTableStatus(cus);
                    }else if(statusCode == HttpURLConnection.HTTP_NOT_FOUND){
                        LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"服务停止");
                        cus.setStatus("1");//停止
                        testSpaceDao.updateIntoTableStatus(cus);
                    }else if(statusCode == HttpURLConnection.HTTP_BAD_GATEWAY || statusCode == 500){
                        LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"启动失败");
                        cus.setStatus("3");//启动失败

                        testSpaceDao.updateIntoTableStatus(cus);
                    }else {
                        LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"服务运行中");
                        cus.setStatus("2");//运行中

                        testSpaceDao.updateIntoTableStatus(cus);
                    }
                }catch(Exception e){
                    LogUtil.WriteToLogFile("当前数据查询遇到问题"+e.getMessage());
                    if(e.getMessage().contains("Connection refused")){
                        LogUtil.WriteToLogFile("客户"+cus.getCustomName()+"服务停止");
                        cus.setStatus("1");//停止
                        testSpaceDao.updateIntoTableStatus(cus);
                        continue;
                    }
                }

            }
        }
    }




    public void runFor5Min(){
        System.out.println("开始111111");
        // 这里是你需要执行的任务逻辑
        Customer customer = new Customer();
        List<Customer> all = testSpaceDao.findAll(customer);
        for (Customer cus :
                all) {
            if (!("标准222".equals(cus.getCustomName()) || "标准223".equals(cus.getCustomName()))) { //标准环境不需要删除状态
                // 当前系统时间
                LocalDateTime now = LocalDateTime.now();

                // 指定的时间

                String dateTimeStr = cus.getUpdateDate();
                System.out.println("dateTimeStrBegin ===== " + dateTimeStr);
                // 移除可能存在的毫秒部分
                if (dateTimeStr.contains(".")) {
                    dateTimeStr = dateTimeStr.split("\\.")[0];
                }
                System.out.println("dateTimeStrafter ===== " + dateTimeStr);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime specifiedDateTime = LocalDateTime.parse(dateTimeStr, formatter);

                // 计算时间差
                Duration duration = Duration.between(specifiedDateTime,now);
                // 获取时间差的各个部分
                long days = duration.toDays();
                long hours = duration.toHours() % 24;
                long minutes = duration.toMinutes() % 60;
                long seconds = duration.getSeconds() % 60;

                // 输出时间差
                System.out.println("时间差为: " + days + " 天 " + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒");


            }

        }
    }
}
